import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { staticRoutes, layoutRoute } from './routes';
import http from '@/utils/request';
import { usePermissionStore } from '@/stores/permission'

const router = createRouter({
  history: createWebHistory(),
  routes: [...staticRoutes, layoutRoute],
  scrollBehavior: () => ({ top: 0 })
});

const whiteList = ['/login', '/404', '/front']; // 新增白名单定义

// 启用路由守卫
router.beforeEach(async (to) => {
  const userStore = useUserStore();
  const permissionStore = usePermissionStore()

  // 1. 白名单精确匹配
  if (whiteList.some(path => to.path.startsWith(path))) {
    return true;
  }

  // 2. 白名单检查
  // 3. 权限路由检查
  const isAuthRoute = to.path.startsWith('/dashboard') || to.meta?.requiresAuth

  // 4. 未登录访问受保护路由
  if (!userStore.token && isAuthRoute) {
    return `/login?redirect=${encodeURIComponent(to.fullPath)}`
  }

  // 5. 已登录处理逻辑
  if (userStore.token) {

    console.log(userStore)

    // 5.1 获取用户信息
    if (!userStore.roles.length) {
      try {
        const infoRes = await http.get('/user/getInfo')
        userStore.roles = infoRes.data.roles
        
        // 5.2 根据角色生成路由
        await permissionStore.generateRoutes(userStore.roles)
        
        // 5.3 动态添加路由
        permissionStore.routes.forEach(route => {
          router.addRoute('layoutRoute', {
            ...route,
            path: route.path.startsWith('/') ? route.path.slice(1) : route.path
          })

          console.log(router,"---router")
        })
      } catch (error) {
        userStore.logout()
        return '/login'
      }
    }
    
    // 5.4 已登录访问登录页跳转首页
    if (to.path === '/login') {
      return '/dashboard'
    }
  }

  return true
})

export default router;